package router;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import common.Constants;

public class Pinger implements Runnable {
	private Thread aThread;
	private Router theRouter;
	private static Logger logger = null;

	public Pinger(Router theRouter) {
		logger = Logger.getLogger(Pinger.class);
		PropertyConfigurator.configure(Constants.LOG_CONFIG);

		this.theRouter = theRouter;
		aThread = new Thread(this);
		aThread.setName("Pinger");
		aThread.start();
	}

	public void run() {

		logger.info("Pinger started");
		int nodeId = 0;
		while (true) {
			String ipAddress = theRouter.getIpAddress(nodeId);

			try {
				InetAddress ip = InetAddress.getByName(ipAddress);
				int currStatus = theRouter.getLinkStatus(nodeId);
				if (currStatus == Constants.LINK_GOOD
						&& !ip.isReachable(Constants.PING_TIMEOUT)) {
					theRouter.changeLinkStatus(nodeId, Constants.LINK_DROP);
				}
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (nodeId == Constants.NUM_OF_NODES - 1) {
				nodeId = 0;
			} else {
				nodeId++;
			}

		}

	}
};
